package com.mama100.rpc.mdp.schedule;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.SchedulerException;
import org.quartz.impl.StdScheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.quartz.JobDetailAwareTrigger;
import org.springframework.stereotype.Service;

import com.mama100.common.zk.DistributedLock;
import com.mama100.rpc.mdp.job.CouponKafkaJob;
import com.mama100.rpc.mdp.job.CustomerBelongTerminalJob;

@Service
public class SingletonInCluster implements ApplicationListener<ContextRefreshedEvent>, ApplicationContextAware {
	protected Logger log = LoggerFactory.getLogger(this.getClass());

	@Resource(name = "couponDbJobLock")
	private DistributedLock couponDbJobLock;

	@Resource
	private CouponKafkaJob couponKafkaJob;
	
	@Resource
	private CustomerBelongTerminalJob CustomerBelongTerminalJob;

	@Resource
	private StdScheduler stdScheduler;

	private BeanFactory applicationContext;

	public static boolean lock = false;

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		
		//开启消息队列监听线程
		CustomerBelongTerminalJob.startWorkThread();
		
		// 开始今天的任务
		log.info("couponDbJobLock OK! ");
		couponKafkaJob.startTodayThread();
		try {
			addJob("couponDbJobExecCronTrigger");
			addJob("couponStartTommorrowWorkThread");
			addJob("couponStopYesTommorrowWorkThread");
			addJob("couponReloadDict");
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
		
		//问题待解决
		if (couponDbJobLock.tryLock(180, TimeUnit.SECONDS)) {
			log.info("couponDbJobLock get lock! ");
			lock = true;
		} else {
			log.info("can't get lock! ");
		}

	}

	private void addJob(String bean) throws SchedulerException {
		log.info("add job " + bean);
		CronTrigger ct = applicationContext.getBean(bean, CronTrigger.class);
		JobDetail jd = (JobDetail) ct.getJobDataMap().get(JobDetailAwareTrigger.JOB_DETAIL_KEY);
		stdScheduler.scheduleJob(jd, ct);
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

}
